package com.my.easypoi.styler;

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.styler.ExcelExportStylerDefaultImpl;
import org.apache.poi.ss.usermodel.*;

public class ExcelStyleUtil extends ExcelExportStylerDefaultImpl {

    public ExcelStyleUtil(Workbook workbook) {
        super(workbook);
        createNumberCellStyler();
    }

    private CellStyle errorCellStyle;

    private void createNumberCellStyler(){
        errorCellStyle=workbook.createCellStyle();
        //设置水平方向字体居中
        errorCellStyle.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直方向字体居中
        errorCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//        errorCellStyle.setDataFormat((short)BuiltinFormats.getBuiltinFormat("#,##0.00"));
        errorCellStyle.setWrapText(true);////设置自动换行;
        //背景色红色
//        errorCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
//        errorCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        Font font = workbook.createFont();
        font.setColor(IndexedColors.RED.getIndex());
        errorCellStyle.setFont(font);
    }

    @Override
    public CellStyle getStyles(boolean noneStyler, ExcelExportEntity entity) {
//        用法
//        @Excel(name = "测试数值类型", dict = "error")
        if (entity != null && "error".equals(entity.getDict())) {
            return errorCellStyle;
        }
        return super.getStyles(noneStyler, entity);
    }

    /**
     * 标题样式
     */
    @Override
    public CellStyle getTitleStyle(short color) {
        CellStyle cellStyle = super.getTitleStyle(color);
        cellStyle.setFont(getFont(workbook, 11, false));
        return cellStyle;
    }
    /**
     * 单元格的样式
     */
    @Override
    public CellStyle stringSeptailStyle(Workbook workbook, boolean isWarp) {
        CellStyle cellStyle = super.stringSeptailStyle(workbook, isWarp);
        cellStyle.setFont(getFont(workbook, 11, false));
        return cellStyle;
    }
    /**
     * 列表头样式
     */
    @Override
    public CellStyle getHeaderStyle(short color) {
        CellStyle cellStyle =  super.getHeaderStyle(color);
        cellStyle.setFont(getFont(workbook, 11, false));
        return cellStyle;
    }
    /**
     * 单元格的样式
     */
    @Override
    public CellStyle stringNoneStyle(Workbook workbook, boolean isWarp) {
        CellStyle cellStyle = super.stringNoneStyle(workbook, isWarp);
        cellStyle.setFont(getFont(workbook, 11, false));
        return cellStyle;
    }

    /**
     * 字体样式
     *
     * @param size   字体大小
     * @param isBold 是否加粗
     * @return
     */
    private Font getFont(Workbook workbook, int size, boolean isBold) {
        Font font = workbook.createFont();
        //字体样式
        font.setFontName("宋体");
        //是否加粗
        font.setBold(isBold);
        //字体大小
        font.setFontHeightInPoints((short) size);
        return font;
    }

}
